<template>
  <p>
    <a-space>
      <a-date-picker v-model:value="queryParams.date"
                     valueFormat="YYYY-MM-DD"
                     :disabled-date="disabledDate"
                     placeholder="请选择出发日期"></a-date-picker>
      <StationSelect v-model="queryParams.start" width="200px" placeholder="请选择出发地"></StationSelect>
      <StationSelect v-model="queryParams.end" width="200px" placeholder="请选择目的地"></StationSelect>
      <a-button type="primary" @click="handleQuery()">查找</a-button>
    </a-space>
  </p>
  <!--表格-->
  <a-table :dataSource="dailyTrainTickets"
           :columns="columns"
           :pagination="pagination"
           @change="handleTableChange"
           :loading="loading"
           :scroll="{ x: 1280 }"
           sticky>
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'operation'">
        <a-space>
          <a-button type="primary" @click="toOrder(record)" :disabled="isExpire(record)">{{isExpire(record) ? "过期" : "预订"}}</a-button>
          <a-button type="primary" @click="showPassStation(record)">途经车站</a-button>
        </a-space>
      </template>
      <template v-else-if="column.dataIndex === 'station'">
        <strong>{{ record.start }}</strong><br>
        <strong>{{ record.end }}</strong>
      </template>
      <template v-else-if="column.dataIndex === 'time'">
        {{ record.startTime }}<br/>
        {{ record.endTime }}
      </template>
      <template v-else-if="column.dataIndex === 'duration'">
        {{ calDuration(record.startTime, record.endTime) }}<br/>
        <div v-if="record.startTime.replaceAll(':', '') >= record.endTime.replaceAll(':', '')">
          次日到达
        </div>
        <div v-else>
          当日到达
        </div>
      </template>
      <template v-else-if="column.dataIndex === 'tdz'">
        <div v-if="record.tdz >= 0">
          <h3 v-if="record.tdz >= 20" class="spare">有</h3>
          <h3 v-else-if="record.tdz === 0" class="grey">已售完</h3>
          <h3 v-else>{{ record.tdz }}</h3>
          {{ record.tdzPrice }}￥
        </div>
        <div v-else>
          --
        </div>
      </template>
      <template v-else-if="column.dataIndex === 'ydz'">
        <div v-if="record.ydz >= 0">
          <h3 v-if="record.ydz >= 20" class="spare">有</h3>
          <h3 v-else-if="record.ydz === 0" class="grey">已售完</h3>
          <h3 v-else>{{ record.ydz }}</h3>
          {{ record.ydzPrice }}￥
        </div>
        <div v-else>
          --
        </div>
      </template>
      <template v-else-if="column.dataIndex === 'edz'">
        <div v-if="record.edz >= 0">
          <h3 v-if="record.edz >= 20" class="spare">有</h3>
          <h3 v-else-if="record.edz === 0" class="grey">已售完</h3>
          <h3 v-else>{{ record.edz }}</h3>
          {{ record.edzPrice }}￥
        </div>
        <div v-else>
          --
        </div>
      </template>
      <template v-else-if="column.dataIndex === 'rw'">
        <div v-if="record.rw >= 0">
          <h3 v-if="record.rw >= 20" class="spare">有</h3>
          <h3 v-else-if="record.rw === 0" class="grey">已售完</h3>
          <h3 v-else>{{ record.rw }}</h3>
          {{ record.rwPrice }}￥
        </div>
        <div v-else>
          --
        </div>
      </template>
      <template v-else-if="column.dataIndex === 'yw'">
        <div v-if="record.yw >= 0">
          <h3 v-if="record.yw >= 20" class="spare">有</h3>
          <h3 v-else-if="record.yw === 0" class="grey">已售完</h3>
          <h3 v-else>{{ record.yw }}</h3>
          {{ record.ywPrice }}￥
        </div>
        <div v-else>
          --
        </div>
      </template>
    </template>
  </a-table>

  <!-- 途经车站 -->
  <a-modal style="top: 30px" v-model:visible="visible" :title="null" :footer="null" :closable="false">
    <a-table :data-source="passStations" :pagination="false">
      <a-table-column key="index" title="站序" data-index="index">
        <template #default="{ index }">
          <strong v-if="index === 0">始发站</strong>
          <strong v-else-if="index === passStations.length - 1">终点站</strong>
          <span v-else>{{ index }}</span>
        </template>
      </a-table-column>
      <a-table-column key="name" title="站名" data-index="name" />
      <a-table-column key="inTime" title="进站时间" data-index="inTime">
        <template #default="{ record }">
          <strong v-if="record.inTime">{{record.inTime}}</strong>
          <span v-else>--</span>
        </template>
      </a-table-column>
      <a-table-column key="outTime" title="出站时间" data-index="outTime">
        <template #default="{ record }">
          {{ record.outTime == null ? '--' : record.outTime }}
        </template>
      </a-table-column>
      <a-table-column key="stopTime" title="停站时长" data-index="stopTime">
        <template #default="{ record }">
          {{ record.stopTime == null ? '--' : record.stopTime }}
        </template>
      </a-table-column>
    </a-table>
  </a-modal>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import request from "@/utils/request";
import {notification} from 'ant-design-vue'
import dayjs from 'dayjs'
import StationSelect from "@/components/StationSelect.vue";
import router from "@/router";

// 表格加载
let loading = ref(false);
// 添加余票信息的属性
let dailyTrainTicket = ref({
  id: undefined,
  date: undefined,
  trainCode: undefined,
  start: undefined,
  startPinyin: undefined,
  startTime: undefined,
  startIndex: undefined,
  end: undefined,
  endPinyin: undefined,
  endTime: undefined,
  endIndex: undefined,
  tdz: undefined,
  tdzPrice: undefined,
  ydz: undefined,
  ydzPrice: undefined,
  edz: undefined,
  edzPrice: undefined,
  rw: undefined,
  rwPrice: undefined,
  yw: undefined,
  ywPrice: undefined
});
// 表格数据
const dailyTrainTickets = ref([]);
// 分页的三个属性名是固定的
const pagination = ref({
  position: ['bottomCenter'],
  total: 0,
  current: 1,
  pageSize: 5,
  showSizeChanger: true,
  pageSizeOptions: ['5', '10', '20']
});
// 表格展示列
const columns = [
  {
    title: '车次编号',
    dataIndex: 'trainCode',
    key: 'trainCode',
  },
  {
    title: '车站',
    dataIndex: 'station',
  },
  {
    title: '时间',
    dataIndex: 'time',
  },
  {
    title: '历时',
    dataIndex: 'duration',
  },
  {
    title: '特等座',
    dataIndex: 'tdz',
    key: 'tdz',
  },
  {
    title: '一等座',
    dataIndex: 'ydz',
    key: 'ydz',
  },
  {
    title: '二等座',
    dataIndex: 'edz',
    key: 'edz',
  },
  {
    title: '软卧',
    dataIndex: 'rw',
    key: 'rw',
  },
  {
    title: '硬卧',
    dataIndex: 'yw',
    key: 'yw',
  },
  {
    title: '操作',
    dataIndex: 'operation',
  }
];

// 查询参数
let queryParams = ref({});
// 请求 -- 查询余票信息
const handleQuery = (param) => {
  // 校验查询参数
  if (Tool.isEmpty(queryParams.value.date)) {
    return notification.error({description: "请选择出发日期"});
  }
  if (Tool.isEmpty(queryParams.value.start)) {
    return notification.error({description: "请选择出发地"});
  }
  if (Tool.isEmpty(queryParams.value.end)) {
    return notification.error({description: "请选择目的地"});
  }
  // 如果无参，则查询当前页
  if (!param) {
    param = {
      pageNum: pagination.value.current,
      pageSize: pagination.value.pageSize
    }
  }
  // 保存查询参数
  SessionStorage.set(SESSION_TICKET_PARAMS, queryParams.value);

  loading.value = true;
  request.get("/business/ticket/list", {
    params: {
      pageNum: param.pageNum,
      pageSize: param.pageSize,
      date: queryParams.value.date,
      start: queryParams.value.start,
      end: queryParams.value.end
    }
  }).then((result) => {
    loading.value = false;
    if (result.status) {
      const date = result.content.records;
      if (date.length === 0) {
        notification.error({description: '没有查询到相关车票信息'});
      }
      dailyTrainTickets.value = date
      // 设置分页控件的值
      pagination.value.current = param.pageNum;
      pagination.value.total = result.content.total;
    } else {
      notification.error({description: result.message});
    }
  });
};

// 计算到达时间 --> 历时时长
const calDuration = (startTime, endTime) => {
  let diff = dayjs(endTime, 'HH:mm').diff(dayjs(startTime, 'HH:mm'), 'seconds');
  let time = dayjs('00:00:00', 'HH:mm').second(diff).format('HH:mm').split(':');
  return `${time[0] == '00' ? '' : time[0] + '时'}${time[1]}分`;
};

// 不能选择今天以前及两周以后的日期
const disabledDate = current => {
  return current && (current <= dayjs().add(-1, 'day') || current > dayjs().add(14, 'day'));
};

// 判断是否过期
const isExpire = (record) => {
  // 标准时间：2000/01/01 00:00:00
  let startDateTimeString = record.date.replace(/-/g, "/") + " " + record.startTime;
  let startDateTime = new Date(startDateTimeString);
  // 当前时间 对比 车票日期
  return new Date().valueOf() >= startDateTime.valueOf();
};

// 请求 -- 途经车站
const passStations = ref([]);
const visible = ref(false)
const showPassStation = record => {
  visible.value = true;
  request.get("/business/daily-train-station/pass", {
    params: {
      date: record.date,
      trainCode: record.trainCode
    }
  }).then(result => {
    if (result.status) {
      passStations.value = result.content;
    } else {
      notification.error({description: result.message});
    }
  });
};

// 表格换页，调用请求
const handleTableChange = (page) => {
  pagination.value = page
  handleQuery({
    pageNum: page.current,
    pageSize: page.pageSize,
  });
};

// 跳转订单
const toOrder = (record) => {
  dailyTrainTicket.value = Tool.copy(record);
  SessionStorage.set(SESSION_ORDER, dailyTrainTicket.value);
  router.push("/order")
};

onMounted(() => {
  queryParams.value = SessionStorage.get(SESSION_TICKET_PARAMS) || {};
  if (Tool.isNotEmpty(queryParams.value)) {
    handleQuery({
      pageNum: 1,
      pageSize: pagination.value.pageSize
    });
  }
});
</script>
